// 机构管理 Mock 数据与接口

// 初始机构列表数据
const tenantList = [
  {
    tenantId: 1,
    tenantCode: 'HSP001',
    tenantName: '智慧医院集团',
    tenantLogo: '/resources/icon.png'
  },
  {
    tenantId: 2,
    tenantCode: 'HSP002',
    tenantName: '市立第一医院',
    tenantLogo: '/src/renderer/public/favicon.ico'
  },
  {
    tenantId: 3,
    tenantCode: 'HSP003',
    tenantName: '高新康复中心',
    tenantLogo: '/src/renderer/src/assets/logo/logo.png'
  }
]

// Mock API 响应封装
function ok(data, message = '操作成功') {
  return { code: 200, msg: message, data }
}

// 列表查询（支持：tenantCode 精确，tenantName 模糊；分页）
export function getTenantList(params = {}) {
  const { pageNum = 1, pageSize = 10, tenantCode = '', tenantName = '' } = params
  let list = [...tenantList]

  if (tenantCode) {
    list = list.filter(item => item.tenantCode === tenantCode)
  }
  if (tenantName) {
    list = list.filter(item => item.tenantName.includes(tenantName))
  }

  const start = (Number(pageNum) - 1) * Number(pageSize)
  const end = start + Number(pageSize)
  return {
    code: 200,
    msg: '查询成功',
    rows: list.slice(start, end),
    total: list.length
  }
}

// 获取详情
export function getTenantDetail(id) {
  const item = tenantList.find(x => x.tenantId === Number(id))
  return item ? ok(item, '获取成功') : { code: 404, msg: '机构不存在', data: null }
}

// 新增机构
export function addTenantMock(data) {
  const exists = tenantList.some(x => x.tenantCode === data.tenantCode)
  if (exists) {
    return { code: 601, msg: '机构编码已存在', data: null }
  }
  const nextId = Math.max(...tenantList.map(x => x.tenantId)) + 1
  const item = { tenantId: nextId, ...data }
  tenantList.push(item)
  return ok(item, '新增成功')
}

// 编辑机构
export function updateTenantMock(data) {
  const index = tenantList.findIndex(x => x.tenantId === Number(data.tenantId))
  if (index === -1) return { code: 404, msg: '机构不存在', data: null }
  tenantList[index] = { ...tenantList[index], ...data }
  return ok(tenantList[index], '修改成功')
}

// 删除机构
export function deleteTenantMock(id) {
  const idx = tenantList.findIndex(x => x.tenantId === Number(id))
  if (idx === -1) return { code: 404, msg: '机构不存在', data: null }
  const removed = tenantList.splice(idx, 1)[0]
  return ok(removed, '删除成功')
}

export default {
  getTenantList,
  getTenantDetail,
  addTenantMock,
  updateTenantMock,
  deleteTenantMock
}

